package cn.tellfish.studydemo.sync;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 数字添加的线程安全
 */
public class IncreaseDemo {


//    private int num = 0;

    private AtomicInteger num = new AtomicInteger(0);

    private Lock lock = new ReentrantLock();

    private void increase(){
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

//        num ++;

//        synchronized (this){
//            num ++;
//        }

//        lock.lock();
//        try {
//            num ++;
//        }finally {
//            lock.unlock();
//        }

        num.addAndGet(1);
    }

    public int getNum() {
//        return num;
        return num.get();
    }

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(500);
        IncreaseDemo increaseDemo = new IncreaseDemo();
        for (int i = 0; i < 500; i++) {
            new Thread(()->{
                latch.countDown();
                try {
                    latch.await();
                    increaseDemo.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }).start();
        }

        while (Thread.activeCount() > 1){
            Thread.yield();
        }

        System.out.println(increaseDemo.getNum());

    }



}
